<?php
class user{
	
	//variables de la classe user
	private $u_login;
	private $u_access;//0:anonyme 1:authentifier 2:admin
	private $u_last_login;
	
	//constructeur
	function __construct() {
		$this->u_access = 0;
		$this->u_login ="anonyme";
		
	}
	//accesseur
	function __get($value){
		if('access' == $value) {
			return $this->u_access;
		}
		elseif('login' == $value){
			return $this->u_login;
		}
		else{
			return "error invalid argument";
		}
	}
	
	function check_password($login,$password){
		$sql_query = mysql_query("Select passwd,access from ".DATABASE_TABLE_USER." WHERE login = '".$login."' ORDER BY `id` ASC") or die(mysql_error());
		while ($query = mysql_fetch_array($sql_query)){
			if (md5($password)==$query['passwd']){
				$this->u_login = $login;
				$this->u_access = $query['access'];
				$this->u_last_login=time();
				mysql_query("UPDATE ".DATABASE_TABLE_USER." SET last_connect = now() WHERE login = '".$login."'")  or die ('Erreur : '.mysql_error());
				
				$timestamp_expire = time() + 10*365*24*3600;
				$cookie_value = md5($query['passwd']+$login);
				setcookie('authen', $cookie_value, $timestamp_expire);
				setcookie('login',$login,$timestamp_expire);
				return true;		
			}
		}	
	return false;
	}
	
	function check_cookie(){
		if (isset($_COOKIE['authen']) and isset($_COOKIE['login']) ){
			$login = mysql_escape_string($_COOKIE['login']);
			$sql_query = mysql_query("Select passwd,access from ".DATABASE_TABLE_USER." WHERE login = '".$login."' ORDER BY `id` ASC") or die(mysql_error());
			while ($query = mysql_fetch_array($sql_query)){
				if (md5($query['passwd']+$login) == $_COOKIE['authen'] ){
					$this->u_login = $login;
					$this->u_access = $query['access'];
					$this->u_last_login=time();
					mysql_query("UPDATE ".DATABASE_TABLE_USER." SET last_connect = now() WHERE login = '".$login."'")  or die ('Erreur : '.mysql_error());
					return true;
				}
				
			}
		}
		return false;
	}
	
	function set_new_password($oldpasswd,$newpasswd){
		$sql_query = mysql_query("Select passwd from ".DATABASE_TABLE_USER." WHERE login = '".$this->u_login."' ORDER BY `id` ASC") or die(mysql_error());
		while ($query = mysql_fetch_array($sql_query)){
			if (md5($oldpasswd)==$query['passwd']){
				$sql_query = mysql_query("UPDATE ".DATABASE_TABLE_USER." SET passwd = '".md5($newpasswd)."' WHERE login = '".$this->u_login."' LIMIT 1");
				return true;
			}
			else{
				$_SESSION['error']="Invalid old passwd";
			}
		}
		return false;
	}
	

}
?>